package com.baizhi.springboot.controller;

import com.baizhi.springboot.entity.Admin;
import com.baizhi.springboot.service.AdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    /*@RequestMapping("/login")
    public String login(Admin admin, String code, HttpSession session, Map map) {
        String relcode = (String) session.getAttribute("relcode");
        String message = "";
        if (!relcode.equals(code)) {
            message = "验证码错误";
            map.put("message", message);
            return "redirect:/login.jsp";
        }


        try {
            Admin admin1 = adminService.login(admin);
            session.setAttribute("admin",admin1);
            return "forward:/main.jsp";

        } catch (Exception e) {
            e.printStackTrace();
            message=e.getMessage();
            map.put("message", message);
            return "forward:/login.jsp";
        }
    }*/
    @RequestMapping("/login")
    public String login(Admin admin, String code, HttpSession session, Map map) {
        String relcode = (String) session.getAttribute("relcode");
        String message = "";
        if (!relcode.equals(code)) {
            message = "验证码错误";
            map.put("message", message);
            return "forward:/login.jsp";
        }


        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(admin.getUsername(),admin.getPassword());
        try {
            subject.login(usernamePasswordToken);
            Admin admin1 = adminService.selectByName(admin.getUsername());
            session.setAttribute("admin",admin1);
            return "redirect:/main.jsp";
        } catch (AuthenticationException e) {
            e.printStackTrace();
            message = "账号或者密码错误";
            map.put("message", message);
            return "forward:/login.jsp";
        }
    }
}
